package com.course.api.service.Impl;

import cn.hutool.core.lang.tree.TreeNodeConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.course.api.entity.Menu;
import com.course.api.mapper.MenuMapper;
import com.course.api.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Autowired
    MenuMapper menuMapper;

    @Override
    public List<Menu> selectTreeMenu(String name) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        List<Menu> list = menuMapper.selectList(queryWrapper);
        List<Menu> parentNodes = list.stream().filter(menu -> menu.getPid() == null).collect(Collectors.toList());
        for (Menu menu : parentNodes) {
            menu.setChildren(list.stream().filter(item -> menu.getId().equals(item.getPid())).collect(Collectors.toList()));
        }
        return parentNodes;
    }

    /**
     * 过滤菜单
     * @param treeMenu
     * @param menuIds
     * @return
     */
    public List<Menu> filterMenu(List<Menu> treeMenu, List<Long> menuIds) {
        List<Menu> roleMenu = new ArrayList<>();
        for (Menu menu : treeMenu) {
            if (menu.getChildren().size() != 0 && !menuIds.contains(menu.getId())) {
                List<Menu> children = menu.getChildren();
                for (int i = 0; i < children.size(); i++) {
                    if (!menuIds.contains(children.get(i).getId())) {
                        children.remove(i--);
                    }
                }
                if (children.size() != 0) {
                    roleMenu.add(menu);
                }
            }
            if (menuIds.contains(menu.getId())) {
                roleMenu.add(menu);
            }
        }
        return roleMenu;
    }
}